#include <stdlib.h>
#include "resizingStack.h"

int initResizingIntStack(resizingstacki *pristack, int length)
{
    pristack->pistack = (int*)calloc(sizeof(int), length);
    if(pristack->pistack == NULL)
        return -1;
    else
    {
        pristack->length = length;
        pristack->top = 0;
    }
    return 0;
}

int isEmptyResizingIntStack(resizingstacki *pristack)
{
    if(pristack->top == 0)
        return 1;
    else
        return 0;
}

int isFullResizingIntStack(resizingstacki *pristack)
{
    if(pristack->top == pristack->length-1)
        return 1;
    else
        return 0;
}

int resizeIntStack(resizingstacki *pristack)
{
    if(pristack->top < pristack->length/4)
    {
        int* newstack = (int*)calloc(sizeof(int),pristack->length/2);
        for(int i = 0; i < pristack->top; i++)
        {
            newstack[i] = pristack->pistack[i];
        }
        free(pristack->pistack);
        pristack->pistack = newstack;
    }
    if(pristack->top > pristack->length*3/4)
    {
        int* newstack = (int*)calloc(sizeof(int), 2*pristack->length);
        for(int i = 0; i < pristack->top; i++)
        {
            newstack[i] = pristack->pistack[i];
        }
        free(pristack->pistack);
        pristack->pistack = newstack;
    }
    return 0;
}

int popResizingIntStack(resizingstacki *pristack)
{
    if(isEmptyResizingIntStack(pristack))
    {
        resizeIntStack(pristack);
        return -1;
    }
    else
    {
       return pristack->pistack[pristack->top--];
    }
}

int pushResizingIntStack(resizingstacki *pristack, int pushitem)
{
    if(isFullResizingIntStack(pristack))
    {
        resizeIntStack(pristack);
    }
    pristack->top++;
    pristack->pistack[pristack->top] = pushitem;
    return 0;
}
